﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractForeEnd;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.ForeEndModels.Basic;
using Newtonsoft.Json;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace HamcoWcs.Service.ForeEnd
{
    public abstract class ForeEndBaseService : IForeEndBaseService
    {
        protected readonly ILoggerService _logger;
        protected readonly WcsDbContext _wcsDbContext;
        protected readonly IMapper _mapper;
        public ForeEndBaseService(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger)
        {
            _logger = logger;
            _wcsDbContext = wcsDbContext;
            _mapper = mapper;
        }

        protected bool CheckQueryDateTime<T>(T t) where T : PageSizeTime
        {
            return t.StartTime != default(DateTime) && t.EndTime != default(DateTime);
        }

        public bool Save()
        {
            return _wcsDbContext.SaveChanges() > 0;
        }

        public bool Save(int count)
        {
            return _wcsDbContext.SaveChanges() == count;
        }

        public async Task<bool> SaveAsync()
        {
            return await _wcsDbContext.SaveChangesAsync() > 0;
        }

        public async Task<bool> SaveAsync(int count)
        {
            return await _wcsDbContext.SaveChangesAsync() == count;
        }

        //public virtual void AddOperationLog(string userName, string msg, [CallerMemberName] string methodName = "")
        //{
        //    if (string.IsNullOrEmpty(userName)) userName = "";
        //    _logger.AddOperationLog(userName, "ForeEnd", methodName, msg);
        //}

        public ForeEndResult AddSystemErrorLog(string errMsg, Exception ex = null)
        {
            if (ex != null) errMsg += $" => {ex.Message}";
            _logger.AddSystemErrorLog("前端：" + errMsg);
            return ForeEndResult.Fail(errMsg);
        }

        public string Serialize<T>(T t)
        {
            return JsonConvert.SerializeObject(t, new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            });
        }
    }
}
